package sh.wnxy.wn38.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sh.wnxy.wn38.entity.Comment;
import sh.wnxy.wn38.entity.Orderitem;
import sh.wnxy.wn38.entity.Spot;
import sh.wnxy.wn38.entity.User;
import sh.wnxy.wn38.service.ICommentService;
import sh.wnxy.wn38.service.IOrderitemService;
import sh.wnxy.wn38.service.ISpotService;
import sh.wnxy.wn38.service.IUserService;
import sh.wnxy.wn38.service.vo.ShowComment;
import sh.wnxy.wn38.service.vo.pinglun;
import sh.wnxy.wn38.utils.Result;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wn38
 * @since 2021-07-14
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/comment")
public class CommentController {
    private ICommentService Com;
    private IUserService Us;
    private IOrderitemService io;
    private ISpotService iSpotService;
    @Autowired
    public void setiSpotService(ISpotService iSpotService) {
        this.iSpotService = iSpotService;
    }
    private ISpotService ac;
    @Autowired
    public void setAc(ISpotService ac) {
        this.ac = ac;
    }

    @Autowired
    public void setCom(ICommentService com) {
        Com = com;
    }

    @Autowired
    public void setUs(IUserService us) {
        Us = us;
    }

    @Autowired
    public void setIo(IOrderitemService io) {
        this.io = io;
    }

    //商品下显示评论
    @PostMapping("/spxpl/{id}")
    public Result spxpl(@PathVariable("id") Integer comtSpotid) {
    /*    QueryWrapper<Comment> ent = new QueryWrapper();
        ent.eq("comt_spotid", 1);
        List<Comment> list = Com.list(ent);
        //取出list集合中某一字段的集合（用户ID）
        List<String> Listid = list.stream().map(Comment::getComtUserid).collect(Collectors.toList());
        //去重
        Set<String> set = new HashSet<>(Listid);
        //因为Mybatis plus中QueryWrapper只接受list所以转回list
        List<String> list2 = new ArrayList<>(set);
        QueryWrapper<User> er = new QueryWrapper();
        er.in("user_id", list2);
        List<User> list1 = Us.list(er);
        // 将id和 对象本身 作为键值对， t -> t 为对象本身 ，为Function.identity()简写
        Map<String, User> map = list1.stream().collect(Collectors.toMap(User::getUserId, t -> t));
        //取出list集合中某一字段的集合（订单ID）
        List<String> dingdanid = list.stream().map(Comment::getComtOiid).collect(Collectors.toList());
        QueryWrapper<Orderitem> wrapper = new QueryWrapper<>();
        wrapper.in("oi_id", dingdanid);
        List<Orderitem> list3 = io.list(wrapper);
        Map<String, Orderitem> map1 = list3.stream().collect(Collectors.toMap(Orderitem::getOiId, t -> t));*/
        ArrayList<ShowComment> showComments = new ArrayList<>();
        QueryWrapper<Comment> ent = new QueryWrapper();
        ent.eq("comt_spotid", comtSpotid);
        List<Comment> list = Com.list(ent);
        for (Comment comment : list) {
            Double comtScore = comment.getComtScore();
            String comtInfo = comment.getComtInfo();
            LocalDateTime gmtModified = comment.getGmtModified();
            String comtUserid = comment.getComtUserid();
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("user_id", comtUserid);
            User one = Us.getOne(userQueryWrapper);
            String userName = one.getUserName();
            ShowComment showComment = new ShowComment(userName, comtScore, comtInfo, gmtModified);
            showComments.add(showComment);
        }
        return Result.ok().data("showComments", showComments);
    }

    @PostMapping("/pinglun/{pageNum}/{pageSize}")
    public Result pinglun(@ApiParam(name = "pageNum", value = "当前页码数", required = true) @PathVariable("pageNum") int pageNum,
                          @ApiParam(name = "pageSize", value = "每页条数", required = true) @PathVariable("pageSize") int pageSize
    ) {
        Double pingfen = 0.0;
        List<Comment> CO = Com.list();
        for (Comment a:CO) {
            pingfen+=a.getComtScore();
        }
        if(CO.size()==0){
            return Result.error();
        }
        Page<Comment> pageTeacher = new Page<>(pageNum, pageSize);
        Com.page(pageTeacher);
        List<Comment> list = pageTeacher.getRecords();
        //取出list集合中某一字段的集合（用户ID）
        List<String> Listid = list.stream().map(Comment::getComtUserid).collect(Collectors.toList());
        List<String> list2 = new ArrayList<>(new HashSet<>(Listid));
        QueryWrapper<User> er = new QueryWrapper();
        er.in("user_id", list2);
        List<User> list1 = Us.list(er);
        // 将id和 对象本身 作为键值对， t -> t 为对象本身 ，为Function.identity()简写
        Map<String, User> map = list1.stream().collect(Collectors.toMap(User::getUserId, t -> t));
        //取出list集合中某一字段的集合（景点ID）
        List<Integer> dingdanid = list.stream().map(Comment::getComtSpotid).collect(Collectors.toList());
        QueryWrapper<Spot> wrapper = new QueryWrapper<>();
        wrapper.in("spot_id", dingdanid);
        List<Spot> ST = ac.list(wrapper);
        System.out.println(ST.size());
        Map<Integer, Spot> collect = ST.stream().collect(Collectors.toMap(Spot::getSpotId, t -> t));
        ArrayList<pinglun> pingluns = new ArrayList<>();
        String format = String.format("%.2f", pingfen / CO.size());
        for (Comment a:list) {
            pingfen+=a.getComtScore();
            pingluns.add(new pinglun(a.getComtOiid(),map.get(a.getComtUserid()).getUserName(),
                    collect.get(a.getComtSpotid()).getSpotName(),a.getGmtCreate(),a.getComtInfo(),
                    a.getComtScore()));
        }
        return Result.ok().data("pinglun",pingluns).data("pingfen",format).data("total",CO.size()/pageSize);
    }
    @PostMapping("/shan/{oiId}")
    public Result shan(@PathVariable("oiId") int oiId){
        QueryWrapper<Comment> er = new QueryWrapper();
        er.eq("comt_oiid", oiId);
        System.out.println(oiId);
        return Com.remove(er)?Result.ok().msg("删除成功") : Result.ok().msg("删除失败");
    }
    @PostMapping("/addComment")
    public Result addComment(@RequestBody Comment comment) {
        System.out.println("88888888888888888888");
        System.out.println(comment.getComtScore());
        System.out.println(comment.getComtOiid());
        System.out.println(comment);
        if (!(comment.getComtScore() == 0.0)) {
            Orderitem order = io.getById(comment.getComtOiid());
            String spotname = order.getOiSpotname();
            Integer id = iSpotService.findByname(spotname);
            String userid = comment.getComtUserid();
            comment.setComtUserid(userid);
            comment.setComtSpotid(id);
            System.out.println("----------------------"+comment);
            boolean save = Com.save(comment);
            UpdateWrapper<Orderitem> wrapper = new UpdateWrapper<Orderitem>();
            wrapper.set("oi_status", 2);

            System.out.println("id------------------"+id);
            System.out.println("userid----------------"+userid);
            System.out.println(wrapper);
            wrapper.eq("oi_id",comment.getComtOiid());
            boolean update = io.update(order, wrapper);
            return Result.ok();
        } else {
            System.out.println("22222222222222222");
            System.out.println(comment.getComtOiid());
            QueryWrapper<Comment> orderitemQueryWrapper = new QueryWrapper<>();
            Comment comment1 = new Comment();
            orderitemQueryWrapper.eq("comt_oiid",comment.getComtOiid());
            Comment one = Com.getOne(orderitemQueryWrapper);
            one.setComtOiid("0");
            return Result.ok().data("Comment",one);

        }
/*
1 WarehouseItem warehouseItem = warehouseItemService.getById(2117733125);
2 UpdateWrapper<WarehouseItem> updateWrapper = new UpdateWrapper<>();
3 //可将指定字段更新为null
4 updateWrapper.set("ownerId", null);
5 updateWrapper.set("product_id",123456);
6 warehouseItemService.update(warehouseItem, updateWrapper);
* */
    }


}

